<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>

<link href="/static/hplus/css/bootstrap.min.css?v=3.4.0"
	rel="stylesheet">
<link href="/static/hplus/css/font-awesome.min.css?v=4.3.0"
	rel="stylesheet">
<script src="/static/hplus/js/jquery-2.1.1.min.js"></script>
<script src="/static/hplus/js/plugins/validate/jquery.validate.min.js"></script>
<script src="/static/hplus/js/bootstrap.min.js?v=3.4.0"></script>
<script type="text/javascript"
	src="/static/js/bootstrap.autocomplete.js"></script>
<script type="text/javascript"
	src="/static/js/doT.min.js"></script>
<script type="text/javascript"
	src="/static/js/serialize.js"></script>
<script type="text/javascript" src="/static/js/autoinputtool.js"></script>
<script type="text/javascript"
	src="/static/bootstrap-table/bootstrap-table.js"></script>



<script type="text/javascript"
	src="/static/bootstrap-contextmenu/bootstrap-contextmenu.js"></script>

<link href="/static/bootstrap-table/bootstrap-table.css"
	rel="stylesheet">

<div id="context-menu">
	<ul class="dropdown-menu" role="menu">
		<li><a tabindex="-1" action="delItm">删除</a></li>
	</ul>
</div>
<div>
	<button class="btn btn-primary" data-toggle="modal" id="openModal"
		data-target="#maintenanceModal" onclick="iniDialog();">新增</button>
</div>
<form id="searchForm">
	<div class="panel panel-default">
		<div class="panel-heading" style="cursor: pointer"
			onclick="moreCriteria();">
			<h4 class="panel-title">
				<a data-toggle="collapse" id="moreCriteria" data-parent="#accordion"
					href="#collapseOne">更多搜索条件</a>
			</h4>
		</div>
		<div id="collapseOne" class="panel-collapse collapse">
			<div class="panel-body">
				<div class="row">
					<div class="col-sm-12 col-xs-12">
						<div class="row">

							<c:forEach var="columnData" items="${columns}">
								<c:if test="${columnData.name!='newHouseAgency'}">
									<div class="col-sm-1">
										<label>${columnData.desc }</label>
									</div>
									<div class="col-sm-2">

										<c:if test="${columnData.type=='base'}">
											<div class="form-group">
												<input type="text" class="form-control"
													name="values[${columnData.name}]"></input>
											</div>
										</c:if>


										<!-- for enum -->
										<c:if test="${columnData.type=='enum'}">
											<div class="form-group">
												<select name="values[${columnData.name}]"
													class="select-block form-control">
													<option value="">请选择</option>
													<c:forEach items="${enums[columnData.name]}" var="entry">
														<option value="<c:out value="${entry.name}" />"><c:out
																value="${entry.label}" /></option>
													</c:forEach>
												</select>
											</div>
										</c:if>
										<!-- for masterdata -->
										<c:if test="${columnData.type=='masterData'}">
											<div class="form-group">
												<input type="text" class="form-control"
													category="${columnData.name}"></input> <input type="hidden"
													name="values[${columnData.name}]"></input>
											</div>
										</c:if>
										<!-- for entities -->
										<c:if test="${columnData.type=='entity'}">

											<div class="form-group">
												<button onclick="openEntity('${columnData.entityType}');"
													type="button" class="form-control">选择${columnData.desc}</button>
												<input type="hidden" name="values[${columnData.name}]"></input>
											</div>

										</c:if>



									</div>
								</c:if>

							</c:forEach>
						</div>
						<div class="row">
							<div class="col-sm-1">
								<button class="btn" type="submit"
									onclick="doSearch(0,100); return false;">搜索</button>
							</div>
							<div class="col-sm-1">
								<button class="btn" type="button"
									onclick="$('#searchForm input').val('');">清除条件</button>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>

</form>
<div class="modal fade in" id="maintenanceModal" tabindex="-1"
	role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	<div class="modal-dialog">

		<form method="post" name="publishForm" id="publishForm"
			class="form-horizontal font14" role="form">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal"
						aria-hidden="true">&times;</button>
					<h4 class="modal-title" id="myModalLabel">修改/新增</h4>
				</div>
				<div class="modal-body">
					<div class="row">
						<c:forEach var="columnData" items="${columns}">
							<c:if test="${columnData.name=='lat'}">
								<c:set var="lat" value="1"></c:set>
							</c:if>
							<c:if test="${columnData.name=='lng'}">
								<c:set var="lng" value="1"></c:set>
							</c:if>

							<c:if test="${columnData.name!='newHouseAgency'}">
								<div class="col-sm-2">
									<label>${columnData.desc }</label>
								</div>
								<div class="col-sm-4">
									<c:if test="${columnData.type=='base'}">
										<div class="form-group">
											<input type="text" class="form-control"
												id="${columnData.name}" name="values[${columnData.name}]"
												<c:if test="${columnData.name=='id'}">
													readOnly="readOnly"
											</c:if>
												id="${columnData.name}"></input>
										</div>
									</c:if>



									<c:if test="${columnData.type=='enum'}">
										<!-- for enum -->
										<div class="form-group">
											<select name="values[${columnData.name}]"
												id="${columnData.name}" class="select-block form-control">
												<c:forEach items="${enums[columnData.name]}" var="entry">
													<option value="<c:out value="${entry.name}" />"><c:out
															value="${entry.label}" /></option>
												</c:forEach>
											</select>
										</div>
									</c:if>
									<c:if test="${columnData.type=='masterData'}">
										<!-- for masterdata -->
										<div class="form-group">
											<input type="text" class="form-control"
												name="values[${columnData.name}]" id="${columnData.name}"
												category="${columnData.name}"></input> <input type="hidden"
												id="${columnData.name}Id"></input>
										</div>
									</c:if>

									<c:if test="${columnData.type=='entity'}">
										<div class="form-group">
											<button onclick="openEntity('${columnData.entityType}');"
												type="button" class="form-control">选择${columnData.desc}</button>
											<input type="hidden" name="values[${columnData.name}]"></input>
										</div>
									</c:if>




									<c:if test="${columnData.type=='enumList'}">
										<!-- for list.. -->

									</c:if>
									<c:if
										test="${columnData.name=='activities' && entity == 'role'}">
										<!-- for permission change: -->
										<div class="form-group">
											<div id="activities"></div>
											<a href="#" onclick="openAuthorizationEditor();"
												role="button" class="btn btn-default popover-test">编辑权限</a>
										</div>
									</c:if>
								</div>
							</c:if>
						</c:forEach>
						<c:if test="${lat=='1' && lng=='1' }">
							<div class="row">
								<div class="col-sm-2">
									<label style="cursor: pointer" onclick="changeMap();">地图编辑</label>
								</div>
							</div>
						</c:if>
					</div>

				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default" id="closeModal"
						data-dismiss="modal">取消</button>
					<button type="button" class="btn btn-success">上传图片</button>
					<button type="submit" class="btn btn-primary">保存</button>
				</div>
			</div>
		</form>
		<!-- /.modal-content -->
	</div>
	<!-- /.modal-dialog -->
</div>
<!-- /.modal -->

<c:if test="${entity == 'role'}">
	<!-- Button trigger modal -->

	<!-- Modal -->
	<div class="modal fade" id="activitiesModal" tabindex="-1"
		role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal">
						<span aria-hidden="true">&times;</span><span class="sr-only">取消</span>
					</button>
					<h4 class="modal-title">编辑权限</h4>
				</div>
				<div class="modal-body">
					<div class="row">
						<div class="col-xs-12">
							<input type="text" class="form-control" id="activityValue"></input>
						</div>
					</div>
					<div class="row">
						<div class="col-xs-12">
							<button class="btn btn-primary" onclick="newActivity();"
								role="button">新增</button>
							<table id="activitiyTable" data-height="300"
								data-show-columns="true" style="cursor: pointer">
								<thead>
									<tr>
										<th data-field="name">权限</th>
										<th data-field="label">权限说明</th>
									</tr>
								</thead>
							</table>
						</div>
					</div>
				</div>
				<div class="modal-footer">
					<!-- <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button> -->
					<button type="button" class="btn btn-primary" data-dismiss="modal">关闭</button>
				</div>
			</div>
		</div>
	</div>
</c:if>

<div id="paging2"></div>

<div id="tableDiv">
	<!-- table-condensed  -->
	<table id="maintenanceTable" data-height="600" data-show-columns="true"
		style="cursor: pointer">
		<thead>
			<tr>

			</tr>
		</thead>
	</table>
</div>
<div id="paging"></div>
<script id="pagetmpl" type="text/template">
<div id="pagingDiv">
  <ul class="pagination">
{{
var pageNo = it.number ;
var pageNo2 = 0;
var totalPages = it.totalPages; 


if(pageNo <= 3) {pageNo2 = 1;}
else{
	if(pageNo > totalPages - 4){
		pageNo2 = totalPages - 4;
	}else{
		pageNo2 = pageNo - 1;
	}
	
}

}}
<li><a href="#page1"  onclick="doSearch(0,100)">首页</a></li>
{{ if(pageNo > 1){ }}
	<li><a href="#page{{= pageNo}}"  onclick="doSearch({{= pageNo - 1}},100)"
{{ }else{ }}
	<li><a href="#page1"  onclick="doSearch(0,100)"
{{ } }}
		>上一页</a></li>
{{for (var i = 0; i < 5; i++){ 
	if(i >= totalPages){continue;}
}}
    <li {{if((pageNo2 + i) == pageNo + 1){}} class="active" {{}}}
		><a href="#page{{= pageNo2 + i}}" onclick="doSearch({{= pageNo2 + i - 1}},100)"
		>{{= pageNo2 + i}}</a></li>
{{	}	}}
{{ if(pageNo < totalPages - 1){ }}
	<li><a href="#page{{= pageNo + 1}}"  onclick="doSearch({{= pageNo + 1}},100)"
{{ }else if(totalPages > 1){ }}
	<li><a href="#page{{= totalPages}}"  onclick="doSearch({{= totalPages - 1}},100)"
{{ }else{ }}
	<li><a href="#page1"  onclick="doSearch(0,100)"
{{ } }}
	>下一页</a></li>
	<li><a href="#page{{= totalPages}}"  onclick="doSearch({{= totalPages - 1}},100)">末页</a></li>
  </ul>
</div>

</script>

<script type="text/javascript">
	var settings = {
		page : 1,
		size : 50
	};
	var entity = "${entity}";

	function doSearch(page, size) {

		settings.page = page;
		settings.size = size;

		var formValue = $("#searchForm").serializeObject();

		$.ajax({
			url : "/sub/maintenanceSingle/member/search/" + settings.page + "/"
					+ settings.size,
			data : formValue,
			type : "POST",
			dataType : "json",
			success : function(data) {

				var columns = [], tableData = [];

				for (var i = 0; i < data.columns.length; i++) {
					console.log(JSON.stringify(data.columns[i]));
					var fieldName = "";

					if (data.columns[i].type == "masterData") {
						fieldName = data.columns[i].name + ".value";
					} else {
						fieldName = data.columns[i].name;
					}

					columns.push({
						field : fieldName,
						title : data.columns[i].desc
					});
				}
				/* console.log(JSON.stringify(data.data.content)); */

				<c:if test="${entity=='role'}">

				for ( var i in data.data.content) {
					var actStr = "";
					var actArray = data.data.content[i].activities;
					if (actArray) {
						for (var j = 0; j < actArray.length; j++) {
							actStr = actStr + "," + actArray[j].label;
						}
						actStr = actStr.substring(1, actStr.length);
					}
					data.data.content[i].activities = actStr;
				}
				</c:if>
				buildTable($("#maintenanceTable"), columns, data.data.content);
				$("#paging div").remove();
				$("#paging2 div").remove();
				$("#paging,#paging2").html(
						doT.template($("#pagetmpl").html())(data.data));
			}
		});
	}
	<c:if test="${entity == 'role'}">
	function newActivity() {

		var id = $("#id").val();
		var activity = $("#activityValue").attr("real-value");
		$.ajax({
			url : "/authorization/grant/" + id + "/" + activity,
			method : "POST",
			success : function(data) {
				buildAutorizationTable();
			}
		});

	}
	$("#activityValue").autocomplete({
		source : function(query, process) {

			$.ajax({
				url : "/authorization/getActivities",
				data : {
					keyword : $("#activityValue").val()
				},
				success : function(data) {
					process(data);
				}
			}).error(function(data) {
				alert("获取出错")
			});
		},
		formatItem : function(item) {
			return item["label"];
		},
		setValue : function(item) {
			//				$(this).nextAll("input:first").val(item["id"]);
			return {
				'data-value' : item["label"],
				'real-value' : item["name"]
			};
		}
	});

	function buildAutorizationTable() {
		var id = $("#id").val();
		if (id == "") {
			return false;
		}
		$.ajax({
			url : "/authorization/getActivities/" + id,
			data : {},
			type : "POST",
			success : function(data) {
				$("#activitiyTable").bootstrapTable('destroy').bootstrapTable({
					data : data
				});

				$('#activitiesModal').modal('show');
			}
		});
	}
	function openAuthorizationEditor() {
		buildAutorizationTable();
		//			$('#activitiesModal').modal('show');
	}
	$("#activityValue").autocomplete({

	});
	</c:if>

	$(function() {
		<c:if test="${entity == 'role'}">

		</c:if>

		$("input[category]").each(function() {
			autoCompleteInput($(this));

		});

		$('#tableDiv')
				.contextmenu(
						{
							target : '#context-menu',
							before : function(e) {
								// This function is optional.
								// Here we use it to stop the event if the user clicks a span
								console.log(e);
								if (e.target) {
									var id = $(e.target.parentElement).attr(
											"entityId");
									//		            	var id = e.target.parent().attr("entityId");
									this.getMenu().find('a[action="delItm"]')
											.attr("entityId", id);
								}
								e.preventDefault();

								return true;
							},
							onItem : function(context, e) {

								var action = $(e.target).attr("action");
								var id = $(e.target).attr("entityId");
								if (action == "delItm") {
									$
											.ajax(
													{
														url : "/sub/maintenanceSingle/member/del/"
																+ id,
														data : {},
														type : "POST",
														error : function(error) {
															console.log(error);
														},
														success : function(data) {
															if (data == "success") {
																iniDialog();
																doSearch(0, 100);
																closeModal();
															} else {
																alert("删除失败");
															}
														}
													}).error(function(data) {
												alert("保存失败。");
												closeModal();
												console.log(data);
											});

									return;
								}
							}
						});
		//initialize the bootstraptable..
		//$("select.select-block").selectpicker({style: 'btn-primary', menuStyle: 'dropdown-inverse'});
		doSearch(0, 100);

	});

	//		function buildTable($el, cells, rows) {
	function buildTable($el, columns, data) {
		var i, j, row;

		/*
		for (i = 0; i < cells; i++) {
			columns.push({
				field : 'field' + i,
				title : 'Cell' + i
			});
		}
		for (i = 0; i < rows; i++) {
			row = {};
			for (j = 0; j < cells; j++) {
				row['field' + j] = 'Row-' + i + '-' + j;
			}
			data.push(row);
		}
		 */
		//		console.log(data);
		//		console.log(columns);
		$el.bootstrapTable('destroy').bootstrapTable({
			columns : columns,
			data : data
		});
	}

	$("#publishForm").validate({
		submitHandler : function(form) {
			var formVal = $("form[name='publishForm']").serializeObject();

			$.ajax({
				url : "/sub/maintenanceSingle/member/save/",
				data : formVal,
				type : "POST",
				error : function(error) {
					console.log(error);
				},
				success : function(data) {
					if (data == "success") {
						iniDialog();
						doSearch(0, 100);
						closeModal();
					} else {
						alert("保存失败");
					}
				}
			}).error(function(data) {
				alert("保存失败。");
				closeModal();
				console.log(data);
			});

			return false;
		}

	});

	$(document).on(
			"click",
			"#maintenanceTable tr",
			function() {
				/**
				 * open private house data and change.
				 **/
				var id = $(this).attr("entityId");
				if (!id) {
					return;
				}

				$.ajax(
						{
							url : "/sub/maintenanceSingle/member/getRecord/"
									+ id,
							data : {},
							type : "POST",
							dataType : "json",
							success : function(data) {
								iniDialog();
								openDialog();
								<c:if test="${entity == 'role'}">
								var activitiesStr = "";
								var activities = data.activities;
								if (activities && activities.length > 0) {
									for ( var i in activities) {
										activitiesStr = activitiesStr + "<br>"
												+ activities[i].label;
									}
									activitiesStr = activitiesStr.substring(4,
											activitiesStr.length);
								}
								$("#activities").html(activitiesStr);
								</c:if>
								
								
								for ( var i in data) {
									var attr = data[i];
									if (attr||attr==0) {
										$("#publishForm #" + i + "").val(attr);

										//								console.log("type of "+ i + " is " + $.type(attr));
										if ($.type(attr) == "object") {
											if (attr["name"]) {
												$("#publishForm #" + i).val(
														attr["name"]);
											}
											if (attr["value"]) {
												$("#publishForm #" + i + "")
														.val(attr["value"]);
											}
											if (attr["id"]) {
												$("#publishForm #" + i + "Id")
														.val(attr["id"]);
											}
											/*
											$("#publishForm [name='category']")
											.val("area");
											 */

											for ( var j in attr) {
												var val = attr[j];
												$(
														"#publishForm #" + i
																+ "." + j + "")
														.val(val);
											}
										}
									}
								}

								var user = data.createBy;
								if (user) {
									$("#creationName").html(
											"<strong>&nbsp;" + user.name
													+ "</strong>&nbsp;");
								}

								var followUps = data.followUps;
								$("#followUpTb").remove();
								if (followUps) {
									$("#followUp").after(
											doT.template(
													$("#followUpTemp").html())(
													followUps));
								}
							}
						}).error(function(data) {
					alert("获取失败");
					console.log(data);
				});

			});
	function iniDialog() {
		$("#publishForm").get(0).reset();
		$("#publishForm input").val("");

	}

	function showModal() {
		$("#maintenanceModal").modal({
			backdrop : 'static'
		});
	}

	function openDialog() {
		$("#openModal").trigger("click");
	}
	function closeModal() {
		$("#closeModal").trigger("click");
	}

	function moreCriteria() {
		$('.panel-collapse').collapse("toggle");
	}

	function changeMap() {
		var lat = $("#lat").val();
		var lng = $("#lng").val();

		var mapWin = window.open("/ifangbang/maintenanceViewMap?lng=" + lng
				+ "&lat=" + lat);
		// todo: open map...
	}

	function changeLocation(lat, lng) {
		$("#lat").val(lat);
		$("#lng").val(lng);
	}

	function openEntity(type) {
		var mapWin = window.open("/ifangbang/maintenanceViewV2Entity?type="
				+ type);
	}

	$(document).on("click", ".btn-success", function() {
		var myid = $("#id").val();

	});
</script>


